package cn.cvs.controller;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SupplierService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.sun.deploy.security.WSeedGenerator;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/sys/supplier")
public class SupplierController {
    private Logger logger = Logger.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;

    @GetMapping("/supplierList")
    public String getSupplierList(Model model, String querySupCode, String querySupName,
                                  @RequestParam(defaultValue = "1") Integer pageIndex){
        List<Supplier> supplierList = new ArrayList<>();
        try{
            // 设置页面容量
            int pageSize = Constants.pageSize;
            // 总数量(表)
            int totalCount = supplierService.getCount(querySupName,querySupCode);
            // 总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            // 控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            supplierList = supplierService.getList(querySupName,querySupCode, pageIndex,pageSize);
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("querySupName",querySupName);
            model.addAttribute("querySupCode",querySupCode);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo", pageIndex);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("SysUserController->getSupplierList: 供货商列表接口访问失败!");
            return "redirect:/toSysError";
        }
        return "supplier/list";
    }

    // 跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    // 跳转到供货商添加页面
    @GetMapping("/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

    // 添加供货商不包括图片
    /*@PostMapping("/add")
    public String add(Supplier supplier, HttpSession session) throws Exception {
        supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (supplierService.add(supplier)){
            return "redirect:supplierList";
        }
        return "supplier/add";
    }*/

    // 添加供货商包括图片
    @PostMapping("/add")
    public String add(Supplier supplier, HttpSession session,
                      HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false)
                      MultipartFile[] attachs) throws Exception {
        String companyLicPicPath = null;        // 企业营业执照
        String orgCodePicPath = null;           // 组织机构代码证
        String errorInfo = null;
        boolean flag = true;
        String path = "D:\\y2\\作业\\ssm_2\\cvs\\web\\statics\\" + File.separator + "uploadFiles";
        logger.info("SupplierController->add: 文件储存路径: " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()){
                if (i == 0){
                    errorInfo = "uploadFileError";
                }else if (i == 1){
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();      // 原文件名
                logger.info("SupplierController->add: 原文件名: " + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);
                logger.info("SupplierController->add: 原文件名后缀: " + prefix);
                int fileSize = 500000;
                logger.info("SupplierController->add: 上传文件大小: " + attach.getSize());
                if (attach.getSize() > fileSize){
                    request.setAttribute(errorInfo,"* 上传大小不能超过500KB");
                    flag = false;
                }else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")){
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.info("SupplierController->add: 新文件名: " + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    // 保存
                    try{
                        attach.transferTo(new File(targetFile, fileName));
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute(errorInfo,"* 上传失败!");
                        flag = false;
                    }
                    if (i == 0){
                        companyLicPicPath = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
                    }else if (i == 1){
                        orgCodePicPath = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
                    }
                }else{
                    request.setAttribute(errorInfo, "* 上传图片格式不正确!");
                    flag = false;
                }
            }
        }
        if (flag){
            supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCompanyLicPicPath(companyLicPicPath);
            supplier.setOrgCodePicPath(orgCodePicPath);
            if (supplierService.add(supplier)){
                return "redirect:supplierList";
            }
        }
        return "supplier/add";
    }

    // 查看供货商详情
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id, Model model) throws Exception {
        logger.info("SupplierController->view 根据id查询用户id");
        Supplier supplier = supplierService.getById(id);
        model.addAttribute(supplier);
        return "supplier/view";
    }

    // 跳转到供货商修改页面
    @GetMapping("/toUpdate/{supId}")
    public String toUpdate(@PathVariable Integer supId, Model model) throws Exception {
        logger.info("SupplierController->toUpdate: 跳转到供货商修改页面" + supId);
        Supplier supplier = supplierService.getById(supId);
        model.addAttribute(supplier);
        return "supplier/update";
    }

    // 修改供货商
    @PostMapping("/update")
    public String update(Supplier supplier, HttpSession session) throws Exception {
        logger.info("SupplierController->update修改供货商");
        supplier.setUpdatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        if (supplierService.update(supplier)) {
            return "redirect:supplierList";
        }
        return "supplier/update";
    }
}
